package com.haojiang.mh.ui.activity

import com.haojiang.mh.R
import com.haojiang.mh.cache.Const
import com.haojiang.mh.cache.MGlobal
import com.haojiang.mh.service.api.JsonCallback
import com.haojiang.mh.service.entity.SleepAdviceBean
import com.haojiang.mh.service.entity.TokenBean
import com.haojiang.mh.ui.base.BaseActivity
import com.haojiang.mh.utils.KLog
import com.haojiang.mh.utils.SpUtil
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import kotlinx.android.synthetic.main.activity_sleep_advice.*

/**
 * 睡眠建议
 *
 * Created by ZapFive on 2019-06-03.
 *
 * wuzhuang@mirahome.me
 */
class SleepAdviceActivity : BaseActivity() {

    private var day: String? = ""//日期

    override fun getLayoutId() = R.layout.activity_sleep_advice

    override fun getTitleName(): String = getString(R.string.text_sleep_advice_question)

    override fun initActivity() {
        day = intent.getStringExtra(Const.EXTRA_DATA)
        day?.let {
            if (day!!.isEmpty()) {
                isInterruptProcess = true
                finish()
            }
        }

    }

    override fun initView() {
        decideToGetDayReport()
    }

    /**
     * 更新显示
     */
    private fun refreshViewWithData(data: SleepAdviceBean.Data?) {
        if (data == null) {
            showToast(R.string.txt_no_report_advice)
            return
        }
        sleep_len_content_view.text = data.sleep_len
        asleep_content_view.text = data.asleep
        deep_content_view.text = data.deep
        rem_content_view.text = data.rem
        light_content_view.text = data.light
        breath_avg_content_view.text = data.breath_avg
        heart_avg_content_view.text = data.heart_avg
        snore_intervention_content_view.text = data.snore_intervention
        body_move_content_view.text = data.body_move
        score_content_view.text = data.score
    }

    //region 接口数据
    private fun decideToGetDayReport() {
        if (SpUtil.isNeedGetToken()) {
            refreshToken(object : OnRefreshTokenSuccessListener {
                override fun onRefreshTokenSuccess() {
                    getSleepAdvice()
                }

            })

        } else {
            getSleepAdvice()
        }
    }

    private fun getSleepAdvice() {
        val url = Const.getAdvice() + SpUtil[Const.DEVICE_WIFI_MAC, ""]
        val queryMap = HashMap<String, String>()
        day?.let{
            queryMap["day"] = day!!
        }

        queryMap["side"] = if (MGlobal.instance.currLeftSide) "left" else "right"
        OkGo.get<SleepAdviceBean>(url).tag(this).params(queryMap).execute(object : JsonCallback<SleepAdviceBean>() {

            override fun onNormalSuccess(response: Response<SleepAdviceBean>) {
                if (response.body().error.isEmpty()) {
                    refreshViewWithData(response.body().data)
                } else {
                    if ("no_report" == response.body().error) {
                        showToast(R.string.txt_no_report_advice)
                    } else {
                        showToast(R.string.tip_get_data_fail)
                    }
                }
            }

            override fun onError(response: Response<SleepAdviceBean>?) {
                super.onError(response)
                showToast(R.string.tip_get_data_fail)
                KLog.e("response: $response")
            }

            override fun onFinish() {
                hideLoadingDialog()
            }
        })
    }

    /**
     * 刷新Token
     */
//    private fun refreshToken() {
//        val url = Const.getToken() + SpUtil[Const.DEVICE_WIFI_MAC, ""]
//        val queryMap = HashMap<String, String>()
//        queryMap["access_key"] = Const.ACCESS_KEY
//        queryMap["secret_key"] = Const.SECRET_KEY
//        OkGo.get<TokenBean>(url).tag(this).params(queryMap).execute(object : JsonCallback<TokenBean>() {
//
//            override fun onNormalSuccess(response: Response<TokenBean>) {
//                if (response.body().error.isEmpty()) {
//                    SpUtil.put(Const.TOKEN_LOCAL, response.body().data?.token ?: "")
//                    SpUtil.put(Const.TOKEN_EXIST_TIME, System.currentTimeMillis())
//                    getSleepAdvice()
//                } else {
//                    hideLoadingDialog()
//                    KLog.e("Token 更新失败 response: $response")
//                    when (response.body().error) {
//                        "key_error" -> KLog.e("公私钥错误")
//                        "mac_error" -> KLog.e("MAC地址格式错误")
//                    }
//                }
//            }
//
//            override fun onError(response: Response<TokenBean>?) {
//                hideLoadingDialog()
//                KLog.e("Token 更新失败 response: $response")
//            }
//        })
//    }
    //endregion
}